import Taro from '@tarojs/taro';
import http from '@utils/http'

export default {
  jscode: '',
  setUserStorage({ appLoginUser }) {
    if (appLoginUser) {
      const { nickname, avatar, sessionId, telephone } = appLoginUser
      Taro.setStorageSync('nickName', nickname)
      Taro.setStorageSync('avatar', avatar)
      Taro.setStorageSync('sessionId', sessionId)
      Taro.setStorageSync('telephone', telephone)
    }
  },
  async initJsCode(){
    const { authCode } = await this.getAuthCode()
    this.jscode = authCode
  },
  getAuthCode() {
    return new Promise(resolve => {
      my.getAuthCode({
        scopes: 'auth_user',
        fail: (error) => console.error('getAuthCode', error),
        success: (res) => resolve(res)
      })
    })
  },
  async register(data) {
    if (process.env.TARO_ENV === 'weapp') {
      return await http.request({
        url: '/login/register',
        data,
        header: { 'content-type': 'application/json' }
      }, false)
    } else if (process.env.TARO_ENV === 'alipay') {
      return await http.request({
        url: '/login/registerZfb',
        data: {
          code: data.jsCode,
          ...JSON.parse(data.encryptedData)
        },
        header: { 'content-type': 'application/json' }
      }, false)
    } else if (process.env.TARO_ENV === 'tt') {
      return await http.request({
        url: '/login/registerDy',
        data: {
          ...data,
          code: data.jsCode,
        },
        header: { 'content-type': 'application/json' }
      }, false)
    }
  },
  async wxLogin() {
    if (process.env.TARO_ENV === 'weapp') { // 微信
      if (!this.jscode) {
        const { code } = await Taro.login()
        this.jscode = code
      }
      return await http.request({
        url: '/login/wxAuthLogin',
        data: { jsCode: this.jscode },
        header: { 'content-type': 'application/json' }
      }, false)
    } else if (process.env.TARO_ENV === 'alipay') { // 支付宝
      // if(!this.jscode){
        const { authCode } = await this.getAuthCode()
        this.jscode = authCode
      // }  

      return await http.request({
        url: '/login/authLogin.json',
        data: { code: this.jscode, belongto: '' },
        header: { 'content-type': 'application/json' }
      }, false)
    } else if (process.env.TARO_ENV === 'tt') { // 抖音
      if (!this.jscode) {
        const { code } = await Taro.login()
        console.log(code)
        this.jscode = code
      }
      return await http.request({
        url: '/login/dyAuthLogin',
        data: { code: this.jscode },
        header: { 'content-type': 'application/json' }
      }, false)
    }
    return {}
  },
  async login() {
    const { status, data } = await this.wxLogin()
    if (status === '666') { // 未登录
      return { isRegister: false }
    } else if (status === '2000000') {
      this.setUserStorage(data)
      return { isRegister: true, data }
    }
  },
  async toLogin({ encryptedData, iv }) {
    if (!encryptedData) {
      Taro.showToast({
        title: '请允许获取手机号进行注册',
        icon: 'none'
      })
      return Promise.reject()
    } else {
      Taro.showToast({
        title: '注册中...',
        icon: 'loading'
      })
      const data = await this.register({
        jsCode: this.jscode,
        iv,
        encryptedData,
      })
      this.setUserStorage(data.data)
      return data;
    }
  },
  setUserInfo() {
    if (process.env.TARO_ENV === 'tt') {
      return Taro.getUserInfo({
        desc: '用户完善账户信息'
      }).then(({ rawData }) => {
        if (rawData) {
          const { nickName, gender, avatarUrl } = JSON.parse(rawData)
          const params = {
            nickName,
            sex: gender === 0 ? '1' : '2',
            avatarUrl
          }
          return http.request({
            url: '/user/modifyUser.json',
            data: params,
          }).then(() => {
            Taro.setStorageSync('nickName', nickName)
            Taro.setStorageSync('avatar', avatarUrl)
            Taro.showToast({
              title: '已完善信息',
              icon: 'success'
            })
            Taro.removeTabBarBadge({
              index: 3
            })
            return Promise.resolve()
          })
        }
      })
    }
    return Taro.getUserProfile({
      desc: '用户完善账户信息'
    }).then(({ rawData }) => {
      if (rawData) {
        const { nickName, gender, avatarUrl } = JSON.parse(rawData)
        const params = {
          nickName,
          sex: gender === 0 ? '1' : '2',
          avatarUrl
        }
        return http.request({
          url: '/user/modifyUser.json',
          data: params,
        }).then(() => {
          Taro.setStorageSync('nickName', nickName)
          Taro.setStorageSync('avatar', avatarUrl)
          Taro.showToast({
            title: '已完善信息',
            icon: 'success'
          })
          Taro.removeTabBarBadge({
            index: 3
          })
          return Promise.resolve()
        })
      }
    })
  }
}
